// pages/cart/index.js
import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from "../../utils/asyncWx.js";
import regeneratorRuntime from "../../lib/runtime/runtime.js"
import { request } from "../../request/index.js"

Page({

    /**
     * 页面的初始数据
     */
    data: {
        address: {},
        cart: [],
        totalPrice: 0,
        totalNum: 0
    },
    onShow() {
        const address = wx.getStorageSync("address");
        let cart = wx.getStorageSync("cart") || [];
        cart = cart.filter(v => v.checked);
        let totalPrice = 0;
        let totalNum = 0;
        cart.forEach(v => {
            totalPrice += v.num * v.goods_price;
            totalNum += v.num;
        });
        this.setData({
            cart,
            totalPrice,
            totalNum,
            address
        });
    },
    /**
     * 点击支付
     * */
    async handleOrderPay() {
        try {
            const token = wx.getStorageSync("token");
            if (!token) {
                wx.navigateTo({
                    url: '/pages/auth/index'
                });
                return;
            } else {
                const orderPrice = this.data.totalPrice;
                const consignee_addr = this.data.address.all;
                let goods = [];
                const cart = this.data.cart;
                cart.forEach(v => goods.push({
                    goods_id: v.goods_id,
                    goods_number: v.num,
                    goods_price: v.goods_price
                }));
                const orderParams = { orderPrice, consignee_addr, goods };
                const { order_number } = await request({ url: "/my/orders/create", method: "post", data: orderParams,  });
                const { pay } = await request({ url: "/my/orders/req_unifiedorder", method: "post", data: { order_number } });
                await requestPayment(pay);
                const res = await request({ url: "/my/orders/chkOrder", method: "post", data: { order_number } });
                showToast({title:"支付成功！"});
                let newCart = wx.getStorageSync("cart");
                newCart = newCart.filter(v=>!v.checked);
                wx.setStorageSync("cart", newCart);
                wx.wx.navigateTo({
                    url: '/pages/order/index'
                });
            }
        } catch (error) {
            showToast({title:"支付失败！"});
            console.log(error);
        }
    }
})